﻿using System;
using System.Web.Mvc;

namespace LaoLuo.Web.Mvc4
{
    public class CaptchaVerifyAttribute : ActionFilterAttribute
    {
        private readonly string _captchaSessionKey;
        private readonly string _modelKey;
        private readonly string _errorMessage;

        /// <summary>
        /// 
        /// </summary>
        public CaptchaVerifyAttribute(string captchaSessionKey, string modelKey, string errorMessage)
        {
            _captchaSessionKey = captchaSessionKey;
            _modelKey = modelKey;
            _errorMessage = errorMessage;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            if (filterContext.RequestContext.HttpContext.Session != null)
            {
                var s = filterContext.RequestContext.HttpContext.Session[_captchaSessionKey];

                if (s != null)
                {
                    var ss = s.ToString();

                    if (!string.IsNullOrWhiteSpace(ss))
                    {
                        if (ss.Equals(filterContext.RequestContext.HttpContext.Request[_modelKey], StringComparison.InvariantCultureIgnoreCase))
                        {
                            return;
                        }
                    }
                }
            }

            filterContext.Controller.ViewData.ModelState.AddModelError(_modelKey, _errorMessage);
        }
    }
}
